/* 与服务器socket链接 */
import io from 'socket.io-client'
import store from '@/store/index'
import { setUserId, setRoomInfo } from '@/store/actions'
import { prepareNewPeerConnection, handleSinglingData } from './webRtc'
import { sq } from './index'
import { putUserInfo } from '@/api/index'

const SERVER = process.env.REACT_APP_IO

let socket = null

/**
 * socket连接
 */
export const connectSocketIo = () => {
  if (socket) {
    return
  }
  const userQuery = sq()

  socket = io(SERVER)
  socket.on('connect', async() => {
    console.log('socket连接成功', socket.id)
    await putUserInfo({
      userId: socket.id,
      nickname: userQuery.nickname,
      avatar: userQuery.avatar
    })
    store.dispatch(setUserId(socket.id))
  })
  socket.on('room-update', async(roomInfo) => {
    console.log('更新room', roomInfo)
    store.dispatch(setRoomInfo(roomInfo))
  })
  socket.on('connect-prepare', (data) => {
    console.log('申请webRtc预连接', data)
    const { connectUserId } = data

    /* 已存在的用户准备webRTC连接, false表示发起方等待接收方准备连接 */
    prepareNewPeerConnection(connectUserId, false)

    /* 通知发起方，我已经准备好进行webRTC连接 */
    socket.emit('connect-init', {
      connectUserId
    })
  })
  socket.on('connect-signal', (data) => {
    handleSinglingData(data)
  })
  socket.on('connect-init', (data) => {
    const { connectUserId } = data // 接收方的userId

    prepareNewPeerConnection(connectUserId, true)
  })
}

/**
 * 加入房间
 */
export const joinRoom = (userId, roomId) => {
  socket.emit('join-room', {
    userId,
    roomId
  })
}

/**
 * 交换信令内容
 */
export const signalPeerData = (data) => {
  socket.emit('connect-signal', data)
}
